package com.wenx.ftpcamel;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FtpUtil {
    static FTPClient ftpClient = null;

    public static void main(String[] args) {
        String url = "10.10.5.213";
        int port = 21;
        String username = "camel";
        String password = "camel";
        Boolean flag = connectFTP(url,port,username,password);
        if(flag){
            List<String> names = getFtpDir();
            System.out.println("names = " + names);
        }
        closeFtp();
    }

    public static Boolean connectFTP(String url, int port, String username, String password) {
        boolean flag = false;
        ftpClient = new FTPClient();
        try {
            //连接
            ftpClient.connect(url, port);
            //登陆
            ftpClient.login(username, password);
            //检查延时
            int reply = ftpClient.getReplyCode();
            //如果延时不在200到300之间，就关闭连接
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return flag;
            }
            flag = true;
        } catch (Exception e) {
            System.out.println(url+"服务连接失败");
        }
        return flag;
    }

    /**
     * 获取ftp服务器目录
     * @return
     */
    public static List<String> getFtpDir(){
        List<String> dirNames = new ArrayList<String>();
        try {
            FTPFile[] files = ftpClient.listDirectories();
            for(FTPFile file : files) {
                dirNames.add(file.getName());
            }
        } catch (IOException e) {
            System.out.println("获取目录失败");
        }
        return dirNames;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp(){
        if (ftpClient!=null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (Exception e) {
                System.out.println("关闭ftp连接");
            }
        }
    }
}
